<?php
/**
 * Created by PhpStorm.
 * User: idcu
 * Date: 2016/3/12
 * Time: 14:05
 */
use Org\Util\Rbac;


function checkArr($_data){
    foreach ($_data as $k=>$item) {
        if($item)
            $data[$k] = $item;
    }
    return $data;
}
//获取当前登录用户ID: 如果尚未登陆，则返回NULL
function getUserId(){
    return session(C('USER_AUTH_KEY'));
}

function getUser(){
    if(getUserId()){
        return D('Crm/User')->field('password',true)->relation(array('role'))->find(getUserId());
    }
}

function getRoles(){
    $user = getUser();
    if($user){
        $roles = $user['role'];

    }
    return $roles;
}

function getAccessList(){
    return Rbac::getAccessList(getUserId());
}

function checkAccess(){
    $accessList = getAccessList();
    return $accessList[strtoupper(MODULE_NAME)][strtoupper(CONTROLLER_NAME)][strtoupper(ACTION_NAME)];
}

function isCs(){
    $roles = getRoles();
    foreach($roles as $k=>$v){
        if($v['id'] == 3){
            return 3;
        }elseif ($v['id'] == 4){
            return 4;
        }
        return $v['id'];
    }
    return false;
}

function generateCustomerNo($date){
    return date('YmdHis',strtotime($date)).rand(1000,9999);
}

//比较数字大小，如果$c部位空，$c>$b
function compareNumber($a,$b,$c=''){
    if($c == ''){ //$c为空
        if($a > $b){ //大于
            return '>';
        }elseif($a <$b){ //小于
            return '<';
        }else{ //等于
            return '=';
        }
    }else{ //$c为不为空
        if($a > $c){ //大于
            return '>';
        }elseif($a <$b){ //小于
            return '<';
        }else{ //介于
            return '=';
        }
    }
}

//通过身份证号获取生日(返回值为时间戳)

function getBirthday($id){
    return date('Y-m-d',strtotime(substr($id,6,4).substr($id,10,2).substr($id,12,2)));
}

function fetchDatetime(){
    return date('Y-m-d H:i:s');
}

function fetchDate(){
    return date('Y-m-d');
}

function strToWhere($str){
    return strpos($str,',') ? array('in',explode(',',$str)) : array('eq',$str);
}

//获得数据字典的文字说明
function getDicName($type,$key){
    $data = M('Dict')->where(array('type'=>$type,'value'=>$key))->find();
    return $data['text'];
}

//科学计数法，还原成字符串
function numToStr($num) {
    if (stripos($num, 'e') === false)
        return $num;
    $num = trim(preg_replace('/[=\'"]/', '', $num, 1), '"'); //出现科学计数法，还原成字符串
    $result = "";
    while ($num > 0) {
        $v = $num - floor($num / 10) * 10;
        $num = floor($num / 10);
        $result = $v . $result;
    }
    return $result;
}

//去除bom头
function prepareJSON($input) {

    //This will convert ASCII/ISO-8859-1 to UTF-8.
    //Be careful with the third parameter (encoding detect list), because
    //if set wrong, some input encodings will get garbled (including UTF-8!)
    $imput = mb_convert_encoding($input, 'UTF-8', 'ASCII,UTF-8,ISO-8859-1');

    //Remove UTF-8 BOM if present, json_decode() does not like it.
    if(substr($input, 0, 3) == pack("CCC", 0xEF, 0xBB, 0xBF)) $input = substr($input, 3);

    return $input;
}

//发送api方法
function apiPost($url, $params=false){
    $appkey = C('APPKEY');
    $appSecret = C('APPSECRET');
    $smartSDK = new \ZL\SmartSDK($appkey, $appSecret);
    $res = $smartSDK->execute($url, $params);
//    echo '<pre>';
//    var_dump($url);
//    var_dump($params);
//    var_dump($res);die;
    saveError($res, $params);//错误日志
    return $res;
}

//根据前台客服id 返回相对应community_id
function getCommunityId($id){
    $data = M('User')->find($id);
    if($data['assistant_map']) {
//        $_data = explode(',', $data['assistant_map']);
//        foreach($_data as $k => $v) {
//            $data1[] = "'$v'";
//        }
//        $dd = implode(',', $data1);
//        return $dd;
        return $data['assistant_map'];
    }
    $cc = M('Community')->where(array('name'=>$data['DEPT_NAME']))->find();
    if($cc) {
        return $cc['id'];
    }
    return false;
}

//根据前台客服id 返回相对应模型_id
function getModelId($modelName = '',$id){
    $data = M('User')->find($id);
    if($data['assistant_map']) {
//        $_data = explode(',', $data['assistant_map']);
//        foreach($_data as $k => $v) {
//            $data1[] = "'$v'";
//        }
//        $dd = implode(',', $data1);
//        return $dd;
        $dd = M($modelName)->where(array('community_id'=>array('in',$data['assistant_map'])))->select();
        foreach ($dd as $v){
            $zid[] = $v['id'];
        }
        return implode(',', $zid);
    }
    $cc = M('Community')->where(array('name'=>$data['DEPT_NAME']))->find();
    if($cc) {
        $dd = M($modelName)->where(array('community_id'=>array('in',$cc['id'])))->select();
        foreach ($dd as $v){
            $zid[] = $v['id'];
        }
        return implode(',', $zid);
    }
    return false;
}

//根据前台客服登录session 取出相对应的小区信息
function getCommunityData($isid=false){
    $id = session(C('USER_AUTH_KEY'));
    $communityId = getCommunityId($id);
    if($isid)
        return $communityId;
    $communityData = M('Community')->where("id IN ($communityId)")->select();
    return $communityData;
}

//错误信息存入日志表
function saveError($res, $params){
    if($res['error']==1){
        $data['data'] = serialize($params);
        $data['error'] = $res['info'];
        $data['time'] = time();
        $data['module'] = MODULE_NAME;
        $data['controller'] = CONTROLLER_NAME;
        $data['action'] = ACTION_NAME;
        M('ErrorLog')->add($data);
    }
}
//查询字段是否有时间戳 有的话转成字符串
function timeToStr($str="Y-m-d", $data){
    foreach ($data as $k=>$v){
        $_data[$k] = $v;
        foreach ($v as $k1=>$v1){
            $has = strpos($k1, 'time');
            if ($has && $v1)
                $_data[$k][$k1] = date($str, $v1);
        }
    }
    return $_data;
}

//pre dump
function myDump($arr){
    header("Content-type: text/html; charset=utf-8");
    echo '<pre>';
    var_dump($arr);
    echo '</pre>';
}
//pre dump
function dd($arr){
    header("Content-type: text/html; charset=utf-8");
    echo '<pre>';
    var_dump($arr);
    echo '</pre>';
    die;
}

//字段 值转成 中文字段
function intToName($data, $array){
    foreach ($data as $k=>$v){
        $_data[$k] = $v;
        foreach ($array as $k1=>$v1) {
            if ($k==$k1) {
              foreach ($v1 as $k2=>$v2) {
                  switch ($v) {
                      case $k2:
                          $_data[$k] = $v2;
                          break;
                  }
              }
            }
        }
    }
    return $_data;
}

//打印excel
function dumpExcel($title, $data, $name='demo'){
//    header('Content-Type: application/vnd.ms-excel');
//    header('Content-Disposition: attachment; filename='.$name.'.xls');
//    header('Pragma: no-cache');
//    header('Expires: 0');
//    echo iconv('utf-8', 'gbk', implode("\t", $title)), "\n";
//    foreach ($data as $value) {
//        echo iconv('utf-8', 'gbk', implode("\t", $value)), "\n";
//    }
    $excel = new \ZL\Excel();
    $excel->dumpExcel($title,$data,$name);
}

//PHP stdClass Object转array
function object_array($array) {
    if(is_object($array)) {
        $array = (array)$array;
    } if(is_array($array)) {
        foreach($array as $key=>$value) {
            $array[$key] = object_array($value);
        }
    }
    return $array;
}

function order_confirm($id,$step){
    if(in_array(session('authId'),C('ORDER_MANAGE')))
        return true;
    
    if($step==1){
        $hour = C('ROB_TIME');
        $searchTime = time()-$hour;
        $where['step']= array('in', '1,2');
        $where['rob_start_time'] = array('elt',$searchTime);
    }
    $where['id'] = $id;
    $data = D('Service/WxOrder')->where($where)->find();
    if($data)
        return true;
    return false;
}

function power_confirm(){
    if(in_array(session('authId'),C('ORDER_MANAGE')))
        return 1;
    else
        return false;
}
function chckRole($role_id=false){
    $data = M('RoleUser')->where(array('role_id'=>$role_id,'user_id'=>session('authId')))->find();
//    dd($data);
    if($data)
        return $data;
    else
        return false;
}

function getWhereSql($where){
    $where_90 = D('Service/WxOrder')->where($where)->fetchSql(true)->select();
    myDump($where_90);die;
    $where_90 = strstr($where_90,'WHERE');
    $preg_match = preg_match('/WHERE(.*)/', $where_90, $matches);
    if($preg_match){
        $where_90 = $matches[1];
        $where_90 = '('.$where_90;
    }
    return $where_90;
}

function repairSend($id){
    $data['id'] = $id;
    $url = 'http://smart.wx91go.com/index.php?g=Home&m=Index&a=Repair&token=ofanap1448334221';
    $res = apiPost($url,$data);
    return $res;
}

function crmSendMsg($dataKey,$dataArr){
    $data['dataKey'] = $dataKey;
    $data['dataArr'] = json_encode($dataArr);
    $url = 'http://smart.wx91go.com/index.php?g=Home&m=Index&a=crmSendMsg&token=ofanap1448334221';
    $res = apiPost($url,$data);
}

function event_log($data){
    $db = M("Qtlog",'tp_','DB_WX');
    $data['time'] = time();
    $data['man'] = 'crm:'.session('authId');
    $db->add($data);
}

function whereTime($name='',$istime=true){
    //时间搜索
    $start_time = I('start_time');
    $end_time = I('end_time');
    if($istime) {
        if ($start_time)
            $start_time = strtotime($start_time);
        if ($end_time)
            $end_time = strtotime($end_time);
    }
    if ($start_time && !$end_time)
        $where[$name] = array('egt',$start_time);
    elseif (!$start_time && $end_time)
        $where[$name] = array('elt',$end_time);
    elseif ($start_time && $end_time)
        $where[$name] = array('BETWEEN',"$start_time,$end_time");
    return $where;
}

function chckNode($str,$uid=false){
    $uid = $uid?$uid:session(C('USER_AUTH_KEY'));

    $role_id = M('RoleUser')->where(['user_id'=>$uid])->find()['role_id'];
    $nodeArr = M('Access')->where(['role_id'=>$role_id])->select();
    $nodeStr = '';
    foreach ($nodeArr as $v) {
        if($nodeStr)
            $nodeStr .= ','.$v['node_id'];
        else
            $nodeStr = $v['node_id'];
    }
    $nodes = explode('/',$str);
//    myDump($role_id);
//    myDump($nodeArr);
//    myDump($nodes);
//    myDump($nodeStr);
    foreach ($nodes as $k=>$v) {
        $ok = M('Node')->where(['name'=>$v,'level'=>$k+1,'id'=>['in',$nodeStr]])->find();
        if(!$ok)
            return false;
    }
    return true;
}